package com.yox.rpc.transport.socket.server;

import com.yox.rpc.entity.RpcRequest;
import com.yox.rpc.entity.RpcResponse;
import com.yox.rpc.handler.RequestHandler;
import com.yox.rpc.registry.ServiceRegistry;
import com.yox.rpc.serializer.CommonSerializer;
import com.yox.rpc.transport.socket.util.ObjectReader;
import com.yox.rpc.transport.socket.util.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * 从 RequestHandler 拆分出来，专门处理线程，接收对象
 */
public class SocketRequestHandlerThread implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SocketRequestHandlerThread.class);

    private Socket socket;
    private RequestHandler requestHandler;
    private CommonSerializer serializer;

    public SocketRequestHandlerThread(Socket socket, RequestHandler requestHandler, CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }

    @Override
    public void run() {
        try (InputStream in = socket.getInputStream();
             OutputStream out = socket.getOutputStream()) {

            // 使用 ObjectReader 获取请求对象
            RpcRequest rpcRequest = (RpcRequest) ObjectReader.readObject(in);

            // 解析接口名，并从注册表中得到服务对象
            String interfaceName = rpcRequest.getInterfaceName();

            // 转发给 RequestHandler 处理方法调用
            Object result = requestHandler.handle(rpcRequest);

            // 将方法执行的结果用 ObjectWriter 发送给客户端
            final RpcResponse<Object> response = RpcResponse.success(result, rpcRequest.getRequestID());
            ObjectWriter.writeObject(out, response, serializer);
        } catch (IOException e) {
            logger.error("调用或者发送时出现错误", e);
        }
    }
}
